package pe.edu.pucp.Seguridad.DAO;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pe.edu.pucp.Modelo.Configuracion;
import pe.edu.pucp.Modelo.Impuesto;
import pe.edu.pucp.Util.HibernateUtil;

public class ConfiguracionDAO {

    public void guardarConfiguracion(Configuracion p){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx =  null;
        try {
            tx =  session.beginTransaction();
            session.update(p);
            tx.commit();
        }catch(Exception e) {
            if (tx!=null) tx.rollback();
        } finally {
            session.close();            
        }        
    } 

    public void guardarImpuesto(Impuesto p){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx =  null;
        try {
            tx =  session.beginTransaction();
            session.update(p);
            tx.commit();
        }catch(Exception e) {
            if (tx!=null) tx.rollback();
        } finally {
            session.close();            
        }        
    }    
    
    public Configuracion buscarConfiguracion(){
        
        Configuracion a = new Configuracion();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            Query query = session.createQuery("from Configuracion "); 
            
            List lista = query.list();
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {    
                a = (Configuracion) iter.next();                    
            }        
            tx.commit();
        }catch(HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
            return a;
        }
    }     
    
    public Impuesto buscarImpuesto(int idpais){
        Impuesto p = new Impuesto();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            Query query = session.createQuery("from Impuesto where idpais = :id  ");   
            query.setInteger("id", idpais);
            List lista = query.list();
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {    
                p = (Impuesto) iter.next();                    
            }        
            tx.commit();
        }catch(HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
            return p;
        }
    } 
    
    
    
}
